/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.swirrel.installer;

import java.awt.Component;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import javax.swing.JTree;
import org.swirrel.annotation.TreeNodesChanged;
import org.swirrel.annotation.TreeNodesInserted;
import org.swirrel.annotation.TreeNodesRemoved;
import org.swirrel.annotation.TreeStructureChanged;
import org.swirrel.listener.SwirrelTreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.event.TreeModelListener;
import org.swirrel.util.MethodCall;

/**
 *
 * @author Gronau
 */
public class TreeModelListenerInstaller extends AbstractListenerInstaller implements SwirrelListenerInstaller {

    public TreeModelListenerInstaller() {
        super(Arrays.<Class<? extends Annotation>>asList(TreeNodesChanged.class,
                TreeNodesInserted.class, TreeNodesRemoved.class, TreeStructureChanged.class),
                Arrays.<Class<?>>asList(JTree.class));
    }

    public boolean isListenerAlreadySet(Object obj) {
       TreeModel model = ((JTree) obj).getModel();
       TreeModelListener[] tmls = (model instanceof DefaultTreeModel)
           ? ((DefaultTreeModel) model).getTreeModelListeners()
           : new TreeModelListener[]{}; //no way to get the listeners
       for(TreeModelListener tml : tmls) {
         if (tml instanceof SwirrelTreeModelListener) {
           return true;
         }
       }
       return false;
    }

    public void registerListener(Field field, Component comp, List<MethodCall> methodCalls) throws IllegalAccessException {
        Object obj = field.get(comp);
        ((JTree)obj).getModel().addTreeModelListener(new SwirrelTreeModelListener(methodCalls.get(0),
                methodCalls.get(1), methodCalls.get(2), methodCalls.get(3)));
    }
}
